package com.lmm.lcuser.lc_user.pages;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.lmm.dresswisdom.lmmframe.components.alert.AlertUtils;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.PackageUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.lmm.lcuser.lc_user.AppBaseActivity;
import com.lmm.lcuser.lc_user.R;
import com.lmm.lcuser.lc_user.commonbean.ShopBean;
import com.lmm.lcuser.lc_user.utils.BDGPSUtils;
import com.lmm.lcuser.lc_user.utils.GPSReturn;
import com.squareup.picasso.Picasso;

import org.json.JSONException;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * @author xmgong
 * @date 2018/4/24
 */

public class ShopMapActivity extends AppBaseActivity implements ShopMapContract.IView, View.OnClickListener {


    MapView mMapView;
    BaiduMap mBaiduMap;
    RelativeLayout relUserLocation;
    RelativeLayout rel_shopinfo;
    LinearLayout linShopDetail, linNavi, linCall;
    TextView tvShopName, tvShopAddress, tvDistance;
    ImageView ivLogo;
    RelativeLayout relBack;


    //用户当前位置
    LatLng userLatLng;
    //地图中心位置
    LatLng centerLatLng;

    BDGPSUtils bdgpsUtils;

    ShopMapPresent mPresent;
    List<ShopBean> allShops = new ArrayList<>();
    BitmapDescriptor shopIcon = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_marker);

    Marker curMark = null;//选中的店铺

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopmap);
        hideActionBar();
        mPresent = new ShopMapPresent(this);
        mMapView = (MapView) findViewById(R.id.map);
        relUserLocation = (RelativeLayout) findViewById(R.id.userLocation);
        rel_shopinfo = (RelativeLayout) findViewById(R.id.rel_shopinfo);
        linShopDetail = (LinearLayout) findViewById(R.id.lin_detail);
        linCall = (LinearLayout) findViewById(R.id.lin_call);
        linNavi = (LinearLayout) findViewById(R.id.lin_navi);
        tvDistance = (TextView) findViewById(R.id.tv_distance);
        tvShopAddress = (TextView) findViewById(R.id.tv_address);
        tvShopName = (TextView) findViewById(R.id.tv_shopname);
        ivLogo = (ImageView) findViewById(R.id.iv_shop_logo);
        relBack = (RelativeLayout) findViewById(R.id.rel_back);

        relBack.setOnClickListener(this);
        linCall.setOnClickListener(this);
        linNavi.setOnClickListener(this);
        linShopDetail.setOnClickListener(this);


        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMaxAndMinZoomLevel(20, 15);
        //设置地图显示类型
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setOnMapStatusChangeListener(listener);
        mBaiduMap.setOnMarkerClickListener(Marklistener);

        relUserLocation.setOnClickListener(this);

        //开始定位
        bdgpsUtils = new BDGPSUtils(gpsReturn, this);
        bdgpsUtils.startGPS();
    }


    private void getList(LatLng latlng) {
        mPresent.getShopLst(latlng);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }


    BaiduMap.OnMapStatusChangeListener listener = new BaiduMap.OnMapStatusChangeListener() {
        /**
         * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
         * @param mapStatus 地图状态改变开始时的地图状态
         */
        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus) {

        }

        /**
         * 因某种操作导致地图状态开始改变。
         * @param mapStatus 地图状态改变开始时的地图状态
         * @param reason 表示地图状态改变的原因，取值有：
         * 1：用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
         * 2：SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
         * 3：开发者调用,导致的地图状态改变
         */
        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus, int reason) {
            if (reason == 1) {
                centerLatLng = mapStatus.target;
                getList(centerLatLng);
            }
        }

        /**
         * 地图状态变化中
         * @param mapStatus 当前地图状态
         */
        @Override
        public void onMapStatusChange(MapStatus mapStatus) {

        }

        /**
         * 地图状态改变结束
         * @param mapStatus 地图状态改变结束后的地图状态
         */
        @Override
        public void onMapStatusChangeFinish(MapStatus mapStatus) {

        }
    };


    BaiduMap.OnMarkerClickListener Marklistener = new BaiduMap.OnMarkerClickListener() {
        /**
         * 地图 Marker 覆盖物点击事件监听函数
         * @param marker 被点击的 marker
         */
        @Override
        public boolean onMarkerClick(Marker marker) {
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(marker.getPosition()));
            rel_shopinfo.setVisibility(View.VISIBLE);
            setShop(marker.getExtraInfo());
            curMark = marker;
            return true;
        }
    };

    GPSReturn gpsReturn = new GPSReturn() {
        @Override
        public void retrunGPSInfo(BDLocation bdLocation) {
            if (bdLocation != null) {
                //当前位置设置到地图中心
                userLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(userLatLng));
                getList(userLatLng);
                markUserLocation();
                bdgpsUtils.stopGPS();
            }
        }
    };

    @Override
    public void setNearShop(List<ShopBean> shops) {
        for (ShopBean shop : shops) {
            if (!allShops.contains(shop)) {
                allShops.add(shop);
                addMark(shop);
            }
        }
    }


    private void addMark(ShopBean shopBean) {
        LatLng point = new LatLng(Double.parseDouble(shopBean.getLat()), Double.parseDouble(shopBean.getLng()));
//构建MarkerOption，用于在地图上添加Marker

        Bundle bundle = new Bundle();
        bundle.putString("shopname", shopBean.getShopName());
        bundle.putString("logo", shopBean.getLogo());
        bundle.putFloat("distance", shopBean.getDistance());
        bundle.putString("address", shopBean.getAddress());
        bundle.putInt("id", shopBean.getShopId());
        bundle.putString("lat", shopBean.getLat());
        bundle.putString("lng", shopBean.getLng());
        bundle.putString("phone", shopBean.getPhone());

        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(shopIcon)
                .alpha((float) 0.8)
                .title(shopBean.getShopName())
                .extraInfo(bundle);

//在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }


    private void markUserLocation() {
        BitmapDescriptor shopIcon = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_location);
        OverlayOptions option = new MarkerOptions()
                .position(userLatLng)
                .icon(shopIcon);
//在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }


    private void setShop(Bundle bundle) {
        float dis = bundle.getFloat("distance");
        DecimalFormat myformat = new DecimalFormat("0.00");
        if (dis > 1) {
            tvDistance.setText("距您" + myformat.format(dis) + "km");
        } else {
            tvDistance.setText("距您" + myformat.format(dis * 1000) + "米");
        }

        tvShopName.setText(bundle.getString("shopname"));
        tvShopAddress.setText(bundle.getString("address"));
        Picasso.with(this).load(bundle.getString("logo")).into(ivLogo);
    }

    @Override
    public void onClick(View v) {
        if (v == relUserLocation) {
            mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(userLatLng));
        } else if (v == linCall) {
            final String phone = curMark.getExtraInfo().getString("phone");
            AlertUtils.showAlert(this, "拨打号码", "是否拨打" + phone + "?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //意图：想干什么事
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_CALL);
                    //url:统一资源定位符
                    //uri:统一资源标示符（更广）
                    intent.setData(Uri.parse("tel:" + phone));
                    //开启系统拨号器
                    startActivity(intent);
                }
            });

        } else if (v == linNavi) {
            String lat = curMark.getExtraInfo().getString("lat");
            String lng = curMark.getExtraInfo().getString("lng");

            if (PackageUtils.isAvilible(this, "com.baidu.BaiduMap")) {
                Intent i1 = new Intent();
                i1.setData(Uri.parse("baidumap://map/navi?location=" + lat + "," + lng));
                startActivity(i1);
            } else {
                ToastUtils.showToastShort("请先安装百度地图");
            }

        } else if (v == linShopDetail) {

        } else if (v == relBack) {
            finish();
        }
    }
}
